﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

 class Sol1005
{
    //先把所有的负数都转成正数，多的k用来转最小的正数或者0
    public int LargestSumAfterKNegations2(int[] nums, int k)
    {

        Array.Sort(nums);
        int cur = 0;

        while (k > 0) {

            Console.WriteLine(nums[cur]);
            if (nums[cur] < 0)//原来的正数变为负数之后会进入这个循环
            {
                nums[cur] = -nums[cur];
                k--;
                cur++;
            }
            else
            {
                nums[cur] = -nums[cur];
                k--;

            }
 
        }
        int sum = 0;
        for (int i = 0; i < nums.Length; i++) { 
            sum += nums[i];
        }



        return sum;

    }
    //先把所有的负数都转成正数，多的k用来转或者1
    public int LargestSumAfterKNegations(int[] nums, int k)
    {

       
        int min = int.MaxValue;
        int minIndex = 0;
        Array.Sort(nums);

        int i = 0;
        //从小到大把负数变正
        while (k > 0 && i < nums.Length)
        {
            if (nums[i] < 0)
            {
                nums[i] = -nums[i];
                k--;
               
            }
          
            i++;
        }
        //找到最小值
        for (int j = 0; j < nums.Length; j++)
        {
            if (min > nums[j])
            {
                min = nums[j];
                minIndex = j;
            }
        }
        //把最小值变负数
        while (k > 0) {

            nums[minIndex] = -nums[minIndex];
            k--;
        }
        int sum = 0;
        for (int j = 0; j < nums.Length; j++)
        {
            sum += nums[j];
        }
        return sum;

    }
}

class Program1005
{

    static void Main1005(string[] args)
    {
        Sol1005 sol1005 = new Sol1005();
        //int[] nums = [3, -1, 0, 2];
        int[] nums = [1, 3, 2, 6, 7, 9];

       int res= sol1005.LargestSumAfterKNegations(nums, 3);
        Console.WriteLine(res);


    }

}